/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved. 
 */
package com.icinfo.cloud.provider.punish.ucaseassist.assistmain.service.impl;

import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamDocumentInfoMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseStageLinkRelateDocumentQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseStageLinkRelateDocumentVo;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.enums.CaseStatusChangeTypeEnum;
import com.icinfo.cloud.provider.punish.ucaseassist.assistmain.mapper.CaseAssistMainInfoMapper;
import com.icinfo.cloud.provider.punish.ucaseassist.assistmain.model.CaseAssistMainInfo;
import com.icinfo.cloud.provider.punish.ucaseassist.assistmain.service.ICaseAssistMainInfoService;
import com.icinfo.cloud.provider.punish.ucaseassist.assistmain.vo.CaseAssistLinkOperateVo;
import com.icinfo.cloud.provider.punish.ucaseassist.assistmain.vo.CaseAssistMainInfosVo;
import com.icinfo.cloud.workflow.config.model.ConfigWorkFlowDocument;
import com.icinfo.cloud.workflow.config.model.ConfigWorkFlowOperateDetailInfo;
import com.icinfo.cloud.workflow.config.service.IConfigWorkFlowDocumentService;
import com.icinfo.cloud.workflow.config.service.IConfigWorkFlowOperateDetailInfoService;
import com.icinfo.cloud.workflow.work.model.WorkFlowRollAssistMainInfo;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 描述: 案件副流程主表 case_assist_main_info 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年08月18日
 */
@Service
public class CaseAssistMainInfoServiceImpl extends MyBatisServiceSupport implements ICaseAssistMainInfoService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseAssistMainInfoServiceImpl.class);

    @Autowired
    private CaseAssistMainInfoMapper caseAssistMainInfoMapper;
    @Autowired
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Autowired
    private IConfigWorkFlowOperateDetailInfoService configWorkFlowOperateDetailInfoService;
    @Autowired
    private ConfigBusiParamDocumentInfoMapper configBusiParamDocumentInfoMapper;
    @Autowired
    private ICaseMainInfoService caseMainInfoService;
    @Autowired
    private IConfigWorkFlowDocumentService configWorkFlowDocumentService;

    /**关联的文书隐藏列表*/ // TODO 要干掉
    public static final List<String> RELATED_HIDE_DOC_LISTS;

    static {
        RELATED_HIDE_DOC_LISTS = new ArrayList<>();
        RELATED_HIDE_DOC_LISTS.add(Constant.STRING_KIND_CODE_SDHZ);
    }

    /**
     * 【V1.4.1】描述：获取案件子（副）流程相关信息总和
     * @author tianrunjia
     * @date 2022-08-18
     * @return
     */
    @Override
    public List<CaseAssistMainInfosVo> getCaseAssistMainInfosList(String caseId) {
        //1、主记录
        List<CaseAssistMainInfosVo> caseAssistMainInfosVoList = caseAssistMainInfoMapper.selectCaseAssistMainInfosList(caseId);
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);

        //根据工作流版本号、工作流编号查询有配对文书目录编码的文书配置信息 TODO 也要优化掉
        String workFlowVersion = caseMainInfo.getCaseFlowVersion();
        String workFlowCode = caseMainInfo.getCaseFlowCode();
        List<ConfigWorkFlowDocument> list =
                configWorkFlowDocumentService.getConfigWorkFlowDocumentMatchedListByFlowCode(workFlowCode,workFlowVersion);
        Map<String,String> matchMapCataLogCode = new HashMap<>(20);
        Map<String,String> matchMapIsMatchDocument = new HashMap<>(20);
        list.forEach(g->{
            matchMapCataLogCode.put(g.getDocumentCatalogCode(),g.getMatchedDocumentCatalogCode());
            matchMapIsMatchDocument.put(g.getDocumentCatalogCode(),g.getIsMatchDocument());
        });

        caseAssistMainInfosVoList.forEach(e->{
            //2、操作
            List<CaseAssistLinkOperateVo> caseAssistLinkOperateVoList = new ArrayList<>();
            List<ConfigWorkFlowOperateDetailInfo> configWorkFlowOperateDetailInfoList = configWorkFlowOperateDetailInfoService.getConfigWorkFlowOperateDetailInfoListByLinkCode(e.getCaseFlowCode(),e.getCaseAssistCurrentLinkCode());
            configWorkFlowOperateDetailInfoList.forEach(f->{
                if(!"CLOSE-TRIGGER-APPROVAL-PASS".equals(f.getRollSignal())){
                    CaseAssistLinkOperateVo operateVo = new CaseAssistLinkOperateVo();
                    operateVo.setOperateCode(f.getWorkOperateCode());
                    operateVo.setOperateName(f.getWorkOperateName());
                    operateVo.setCatalogCode(f.getDocumentCatalogCode());
                    operateVo.setFrontSymble(f.getFrontSymble());
                    caseAssistLinkOperateVoList.add(operateVo);
                }
            });
            e.setAssistOperateList(caseAssistLinkOperateVoList);
            //3、文书记录 TODO 非常不合理，必须优化
            CaseStageLinkRelateDocumentQueryDto query = new CaseStageLinkRelateDocumentQueryDto();
            query.setCaseId(caseId);
            query.setCaseAssistId(e.getId());
            List<CaseStageLinkRelateDocumentVo> caseStageLinkRelateDocumentList
                    = caseDocumentRecordService.getCaseStageLinkRelateDocumentInfo(query);



            //List<CaseDocumentRecordDto> caseDocumentRecordDtoList = caseDocumentRecordService.getCaseDocumentRecordList(caseId,e.getId());
            List<CaseStageLinkRelateDocumentVo> caseStageLinkRelateDocumentVoList = new ArrayList<>();
            caseStageLinkRelateDocumentList.forEach(h->{
                String documentCatalogCode = h.getDocumentCatalogCode();
                String kindCode = h.getDocumentKindCode();
                //无奈之举，想办法优化 TODO
                h.setMatchDocumentCatalogCode(matchMapCataLogCode.get(documentCatalogCode));
                h.setIsMatchDocument(matchMapIsMatchDocument.get(documentCatalogCode));
                //根据文书目录编码查询关联文书
                List<String> allRelationDocCatalogCodeList = getALLRelationDocCatalogCodeList(caseMainInfo.getBusiParamId(), documentCatalogCode);
                h.setAllRelationDocCatalogCodeList(allRelationDocCatalogCodeList);
                if(CaseStatusChangeTypeEnum.isCaseChangeDocEnum(kindCode)){
                    h.setCaseDocumentTypeFlag(Constant.STRING_1);
                }
                //设置文书为有效状态
                h.setIsInvalid("0");

                String documentStatus = h.getDocumentRecordStatus();
                if(!DocumentRecordStatusEnum.WITHDRAW.getCode().equals(documentStatus)){
                    caseStageLinkRelateDocumentVoList.add(h);
                }
            });
            e.setCaseDocumentRecordDtoList(caseStageLinkRelateDocumentVoList);
        });
        return caseAssistMainInfosVoList;
    }

    /**
     * 获取所有关联文书 TODO 重复了，别的方法里也有
     * @author liyafeng
     * @date 2022/7/29
     * @param busiParamId
     * @param documentCatalogCode
     * @return {@link List< String>}
     */
    private List<String> getALLRelationDocCatalogCodeList(String busiParamId, String documentCatalogCode) {
        List<String> allRelationDocCatalogCodeList=new ArrayList<>();
        Example example=new Example(ConfigBusiParamDocumentInfo.class);
        example.createCriteria().andEqualTo("busiParamId",busiParamId).andEqualTo("documentCatalogCode",documentCatalogCode).andEqualTo("isDeleted","0");
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos=configBusiParamDocumentInfoMapper.selectByExample(example);
        if(null!=configBusiParamDocumentInfos&&configBusiParamDocumentInfos.size()>0) {
            String allRelationDocCatalogCode = "";
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfos.get(0);
            if (StringUtils.isBlank(configBusiParamDocumentInfo.getRelationDocumentCatalogCode())) {
                allRelationDocCatalogCode = documentCatalogCode;
            } else {
                allRelationDocCatalogCode = documentCatalogCode + "," + configBusiParamDocumentInfo.getRelationDocumentCatalogCode();
            }
            allRelationDocCatalogCodeList = Arrays.asList(allRelationDocCatalogCode.split(","));
        }
        return allRelationDocCatalogCodeList;
    }

    /**
     * 【V1.4.1】描述：获取案件子（副）流程相关信息保存
     * @author tianrunjia
     * @date 2022-08-18
     * @return
     */
    @Override
    public String saveCaseAssistMainInfo(WorkFlowRollAssistMainInfo workFlowRollAssistMainInfo) {
        String caseAssistId = workFlowRollAssistMainInfo.getId();
        CaseAssistMainInfo caseAssistMainInfo = new CaseAssistMainInfo();
        caseAssistMainInfo.setId(caseAssistId);
        caseAssistMainInfo.setCaseId(workFlowRollAssistMainInfo.getWorkId());
        caseAssistMainInfo.setCaseAssistFlowName(workFlowRollAssistMainInfo.getWorkAssistCurrentStageName());
        caseAssistMainInfo.setCaseAssistFlowCode(workFlowRollAssistMainInfo.getWorkAssistCurrentStageCode());
        caseAssistMainInfo.setCreateUserId(UserUtil.getUserInfo().getUserId().toString());
        caseAssistMainInfo.setCreateUserName(UserUtil.getUserInfo().getRealName());
        caseAssistMainInfo.setCreateTime(LocalDateTime.now());
        caseAssistMainInfo.setCaseFlowCode(workFlowRollAssistMainInfo.getWorkFlowCode());
        caseAssistMainInfo.setCaseFlowVersion(workFlowRollAssistMainInfo.getWorkFlowVersion());
        caseAssistMainInfo.setCaseAssistCurrentLinkName(workFlowRollAssistMainInfo.getWorkAssistCurrentLinkName());
        caseAssistMainInfo.setCaseAssistCurrentLinkCode(workFlowRollAssistMainInfo.getWorkAssistCurrentLinkCode());
        caseAssistMainInfo.setCaseAssistFlowStatus(workFlowRollAssistMainInfo.getWorkAssistBusiStatus());
        caseAssistMainInfoMapper.insert(caseAssistMainInfo);
        return caseAssistId;
    }

    /**
     * 【V1.4.1】描述：获取案件子（副）流程相关信息更新
     * @author tianrunjia
     * @date 2022-08-18
     * @return
     */
    @Override
    public void modCaseAssistMainInfo(WorkFlowRollAssistMainInfo workFlowRollAssistMainInfo) {
        CaseAssistMainInfo caseAssistMainInfo = new CaseAssistMainInfo();
        caseAssistMainInfo.setId(workFlowRollAssistMainInfo.getId());
        caseAssistMainInfo.setCaseAssistFlowStatus(workFlowRollAssistMainInfo.getWorkAssistBusiStatus());
        caseAssistMainInfo.setCaseAssistCurrentLinkCode(workFlowRollAssistMainInfo.getWorkAssistCurrentLinkCode());
        caseAssistMainInfo.setCaseAssistCurrentLinkName(workFlowRollAssistMainInfo.getWorkAssistCurrentLinkName());
        caseAssistMainInfoMapper.updateByPrimaryKeySelective(caseAssistMainInfo);
    }

    /**
     * 【V1.4.1】描述：获取案件子（副）流程主信息
     * @author tianrunjia
     * @date 2022-08-30
     */
    @Override
    public CaseAssistMainInfo doGetCaseAssistMainInfoById(String caseAssistId) {
        return caseAssistMainInfoMapper.selectByPrimaryKey(caseAssistId);
    }
}